<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <div class="icon-location-box">
        <div class="icon-location"></div>
      </div>
      <div class="location-text">
        广西平南县<i class="fa fa-caret-down"></i>
      </div>
    </header>

    <!-- search部分 -->
    <!-- 
				    搜索框部分（此块与search-fixed-top块宽度高度一致，用于当
					search-fixed-top块固定后，挡住下面块不要窜上去） 
				-->
    <div class="search">
      <!-- 当滚动条超过上面的定位块时，search-fixed-top块变成固定在顶部。 -->
      <div class="search-fixed-top" ref="fixedBox">
        <!-- 搜索框部分中间的白框 -->
        <!-- <div class="search-box">
          
        </div> -->
        <el-input 
          v-model="searchKeyword" 
          :suffix-icon="Search" 
          :loading="isLoading"
          style="width: 88%;height: 9vw;" 
          placeholder="搜索商家" 
          @input="handleSearch"
          clearable
        />
      </div>
    </div>

    <!-- 点餐分类部分 -->
    <ul class="foodtype">
      <li v-for="type in foodTypes" :key="type.typeId" @click="toBusinessList(type.typeId)">
        <img :src="type.foodTypeImg" :alt="type.typeName" />
        <p>{{ type.typeName }}</p>
      </li>
    </ul>

    <!-- 横幅广告部分（注意：此处有背景图片） -->
    <div class="banner">
      <h3>品质套餐</h3>
      <p>搭配齐全吃得好</p>
      <a>立即抢购 &gt;</a>
    </div>

    <!-- 超级会员部分
    <div class="supermember">
      <div class="left">
        <img src="../assets/img/super_member.png" />
        <h3>超级会员</h3>
        <p>&#8226; 每月享超值权益</p>
      </div>
      <div class="right">立即开通 &gt;</div>
    </div> -->

    <!-- 推荐商家部分 -->
    <div class="recommend">
      <div class="recommend-line"></div>
      <p>推荐商家</p>
      <div class="recommend-line"></div>
    </div>

    <!-- 推荐方式部分 -->
    <ul class="recommendtype">
      <li>综合排序<i class="fa fa-caret-down"></i></li>
      <li>距离最近</li>
      <li>销量最高</li>
    </ul>

    <!-- 推荐商家列表部分 -->
    <ul class="business">
      <li v-for="business in businessList" 
          :key="business.businessId"
          @click="toBusinessInfo(business.businessId)">
        <img :src="handleImageUrl(business.businessImg)" />
        <div class="business-info">
          <div class="business-info-h">
            <h3>{{ business.businessName }}</h3>
            <div class="business-info-like">&#8226;</div>
          </div>
          <div class="business-info-star">
            <div class="business-info-star-left">
              <i v-for="index in 5" 
                 :key="index" 
                 class="fa fa-star" 
                 :class="{ 'active': index <= business.averageRating }">
              </i>
              <p>{{ business.averageRating.toFixed(1) }} 月售{{ business.monthlySales || 0 }}单</p>
            </div>
            <div class="business-info-star-right">蜂鸟专送</div>
          </div>
          <div class="business-info-delivery">
            <p>&#165;{{ business.startPrice }}起送 | &#165;{{ business.deliveryPrice }}配送</p>
            <p>3.22km | 30分钟</p>
          </div>
          <div class="business-info-explain">
            <div>{{ business.businessExplain }}</div>
          </div>
          <div class="business-info-promotion">
            <div class="business-info-promotion-left">
              <div class="business-info-promotion-left-incon">新</div>
              <p>咪咕新用户首单立减9元</p>
            </div>
            <div class="business-info-promotion-right">
              <p>2个活动</p>
              <i class="fa fa-caret-down"></i>
            </div>
          </div>
          <div class="business-info-promotion">
            <div class="business-info-promotion-left">
              <div class="business-info-promotion-left-incon">特</div>
              <p>特价商品5元起</p>
            </div>
          </div>
        </div>
      </li>
    </ul>

    <!-- 底部菜单部分 -->
    <Footer></Footer>

    <!-- 在商家列表部分添加 -->
    <div v-if="isSearching && businessList.length === 0" class="empty-result">
      <el-empty description="暂无相关商家" />
    </div>

    <div v-if="searchError" class="search-error">
      <p>{{ searchError }}</p>
      <el-button size="small" @click="retrySearch">重试</el-button>
    </div>
  </div>
</template>

<script setup>
import Footer from "../components/Footer.vue";
import { Search } from '@element-plus/icons-vue'
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { listFoodType } from '../api/foodType';
import { listBusiness, searchBusiness } from '../api/business';
import { ElMessage } from 'element-plus';
import { handleAvatarUrl, handleImageUrl } from '@/utils/imageUtils';

const router = useRouter();
const fixedBox = ref(null);
const input = ref();
const foodTypes = ref([]); // 食品类型列表
const businessList = ref([]); // 商家列表
const searchKeyword = ref('');
const isSearching = ref(false);
const isLoading = ref(false);
const searchError = ref('');

const DEBOUNCE_DELAY = 300; // 减少延迟时间，提高响应速度
const MIN_SEARCH_LENGTH = 1;

// 获取食品类型列表
const getFoodTypes = async () => {
  try {
    const res = await listFoodType();
    
    if (res.code === 0 && Array.isArray(res.data)) {
      foodTypes.value = res.data.map(item => ({
        ...item,
        foodTypeImg: `/src/assets/img/${item.foodTypeImg}`
      }));
    } else {
      console.error('获取食品类型列表失败：数据格式错误', res);
      ElMessage.error('获取食品类型失败');
    }
  } catch (error) {
    console.error('获取食品类型列表失败:', error);
    ElMessage.error('获取食品类型失败');
  }
};

// 获取商家列表
const getBusinessList = async () => {
  try {
    const res = await listBusiness();
    
    if (res.code === 0 && Array.isArray(res.data)) {
      businessList.value = res.data;
    } else {
      console.error('获取商家列表失败：数据格式错误', res);
      ElMessage.error('获取商家列表失败');
    }
  } catch (error) {
    console.error('获取商家列表失败:', error);
    ElMessage.error('获取商家列表失败');
  }
};

// 搜索处理函数
const handleSearch = debounce(async () => {
  const keyword = searchKeyword.value.trim();
  if (keyword.length < MIN_SEARCH_LENGTH) {
    if (isSearching.value) {
      isSearching.value = false;
      await getBusinessList();
    }
    return;
  }

  try {
    searchError.value = '';
    isLoading.value = true;
    isSearching.value = true;
    const res = await searchBusiness(keyword);
    
    if (res.code === 0 && Array.isArray(res.data)) {
      businessList.value = res.data;
    } else {
      ElMessage.error('搜索失败');
    }
  } catch (error) {
    searchError.value = '搜索失败，请重试';
    console.error('搜索失败:', error);
  } finally {
    isLoading.value = false;
  }
}, DEBOUNCE_DELAY);

// 防抖函数
function debounce(fn, delay) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

onMounted(() => {
  getFoodTypes();
  getBusinessList(); // 添加获取商家列表

  // 滚动事件处理
  document.onscroll = () => {
    let s1 = document.documentElement.scrollTop;
    let s2 = document.body.scrollTop;
    let scroll = s1 == 0 ? s2 : s1;
    let width = document.documentElement.clientWidth;
    let search = fixedBox.value;

    if (scroll > width * 0.12) {
      search.style.position = "fixed";
      search.style.left = "0";
      search.style.top = "0";
    } else {
      search.style.position = "static";
    }
  };
});

onUnmounted(() => {
  document.onscroll = null;
});

const toBusinessList = (foodTypeId) => {
  router.push({
    path: "/businessList",
    query: { foodTypeId: foodTypeId },
  });
};

const toBusinessInfo = (businessId) => {
  router.push({
    path: "/businessInfo",
    query: { 
      businessId,
      from: 'index'
    }
  });
};

const retrySearch = () => {
  searchError.value = '';
  handleSearch();
};
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #ff7043;

  display: flex;
  align-items: center;
}

.wrapper header .icon-location-box {
  width: 3.5vw;
  height: 3.5vw;
  margin: 0 1vw 0 3vw;
}

.wrapper header .location-text {
  font-size: 4.5vw;
  font-weight: 700;
  color: #fff;
}

.wrapper header .location-text .fa-caret-down {
  margin-left: 1vw;
}

/****************** search ******************/
.wrapper .search {
  width: 100%;
  height: 13vw;
}

.wrapper .search .search-fixed-top {
  width: 100%;
  height: 13vw;
  background-color: #ff7043;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease; /* 添加过渡效果 */
  z-index: 1000;
}

.wrapper .search .search-fixed-top .search-box {
  width: 88%;
  height: 9vw;
  background-color: #fff;
  border-radius: 14px;

  display: flex;
  justify-content: center;
  align-items: center;

  font-size: 3.5vw;
  color: #aeaeae;
  font-family: "宋体";
  /*此样式是让文本选中状态无效*/
  user-select: none;
}

.wrapper .search .search-fixed-top .search-box .fa-search {
  margin-right: 1vw;
}

/****************** 点餐分类部分 ******************/
.wrapper .foodtype {
  width: 100%;
  height: 48vw;

  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  /*要使用align-content。10个子元素将自动换行为两行，而且两行作为一个整体垂直居中*/
  align-content: center;
}

.wrapper .foodtype li {
  /*一共10个子元素，通过计算，子元素宽度在16.7 ~ 20 之间，才能保证换两行*/
  width: 18vw;
  height: 20vw;

  display: flex;
  /*弹性盒子主轴方向设为column，然后仍然是垂直水平方向居中*/
  flex-direction: column;
  justify-content: center;
  align-items: center;

  user-select: none;
  cursor: pointer;
}

.wrapper .foodtype li img {
  width: 12vw;
  height: 12vw;
  object-fit: cover; /* 确保图片比例正确 */
}

.wrapper .foodtype li p {
  font-size: 3.2vw;
  color: #666;
}

/****************** 横幅广告部分 ******************/
.wrapper .banner {
  /**
		 * 设置容器宽度95%，然后水平居中，这样两边留白; 
		 * 这里不能用padding，因为背景图片也会覆盖padding
		 */
  width: 95%;
  margin: 0 auto;
  height: 29vw;

  /*此三个样式组合，可以保证背景图片充满整个容器*/
  background-image: url(../assets/img/index_banner.png);
  background-repeat: no-repeat;
  background-size: cover;

  box-sizing: border-box;
  padding: 2vw 6vw;
}

.wrapper .banner h3 {
  font-size: 4.2vw;
  margin-bottom: 1.2vw;
}

.wrapper .banner p {
  font-size: 3.4vw;
  color: #666;
  margin-bottom: 2.4vw;
}

.wrapper .banner a {
  font-size: 3vw;
  color: #c79060;
  font-weight: 700;
}

/****************** 超级会员部分 ******************/
.wrapper .supermember {
  /*这里也设置容器宽度95%，不能用padding，因为背景色也会充满padding*/
  width: 95%;
  margin: 0 auto;
  height: 11.5vw;
  background-color: #feedc1;
  margin-top: 1.3vw;
  border-radius: 2px;
  color: #644f1b;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .supermember .left {
  display: flex;
  align-items: center;
  margin-left: 4vw;
  user-select: none;
}

.wrapper .supermember .left img {
  width: 6vw;
  height: 6vw;
  margin-right: 2vw;
}

.wrapper .supermember .left h3 {
  font-size: 4vw;
  margin-right: 2vw;
}

.wrapper .supermember .left p {
  font-size: 3vw;
}

.wrapper .supermember .right {
  font-size: 3vw;
  margin-right: 4vw;
  cursor: pointer;
}

/****************** 推荐商家部分 ******************/
.wrapper .recommend {
  width: 100%;
  height: 14vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .recommend .recommend-line {
  width: 6vw;
  height: 0.2vw;
  background-color: #888;
}

.wrapper .recommend p {
  font-size: 4vw;
  margin: 0 4vw;
}

/****************** 推荐方式部分 ******************/
.wrapper .recommendtype {
  width: 100%;
  height: 5vw;
  margin-bottom: 5vw;
  display: flex;
  justify-content: space-around; /* 保持三个选项均匀分布 */
  align-items: center;
}

.wrapper .recommendtype li {
  font-size: 3.5vw;
  color: #555;
}

/****************** 推荐商家列表部分 ******************/
.wrapper .business {
  width: 100%;
  margin-bottom: 14vw;
}

.wrapper .business li {
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  user-select: none;
  border-bottom: solid 1px #ddd;

  display: flex;
  transition: transform 0.2s ease;
  background: #fff;
  margin-bottom: 2vw;
  border-radius: 2vw;
  overflow: hidden;
  cursor: pointer;
}

.wrapper .business li:active {
  transform: scale(0.98);
}

.wrapper .business li img {
  width: 18vw;
  height: 18vw;
  border-radius: 2vw;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.wrapper .business li .business-info {
  width: 100%;
  box-sizing: border-box;
  padding: 2vw 3vw;
}

.wrapper .business li .business-info .business-info-h {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.5vw;
}

.wrapper .business li .business-info .business-info-h h3 {
  font-size: 4.2vw;
  font-weight: 600;
  color: #333;
}

.wrapper .business li .business-info .business-info-h .business-info-like {
  width: 1.6vw;
  height: 3.4vw;
  background-color: #666;
  color: #fff;
  font-size: 4vw;
  margin-right: 4vw;

  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .business li .business-info .business-info-star {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
  font-size: 3.1vw;
}

.wrapper
  .business
  li
  .business-info
  .business-info-star
  .business-info-star-left {
  display: flex;
  align-items: center;
}

.wrapper
  .business
  li
  .business-info
  .business-info-star
  .business-info-star-left
  .fa-star {
  color: #ddd; /* 未选中的星星颜色 */
  margin-right: 0.5vw;
}

.wrapper
  .business
  li
  .business-info
  .business-info-star
  .business-info-star-left
  .fa-star.active {
  color: #fec80e; /* 选中的星星颜色 */
}

.wrapper
  .business
  li
  .business-info
  .business-info-star
  .business-info-star-left
  p {
  color: #666;
  margin-left: 1vw;
}

.wrapper
  .business
  li
  .business-info
  .business-info-star
  .business-info-star-right {
  background-color: #0097ff;
  color: #fff;
  font-size: 2.4vw;
  border-radius: 2px;
  padding: 0 0.6vw;
}

.wrapper .business li .business-info .business-info-delivery {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 2vw 0;

  color: #666;
  font-size: 3.2vw;
}

.wrapper .business li .business-info .business-info-explain {
  display: flex;
  align-items: center;
  margin-bottom: 3vw;
}

.wrapper .business li .business-info .business-info-explain div {
  display: inline-block;
  padding: 0.5vw 1.5vw;
  border: 1px solid #eee;
  border-radius: 3px;
  font-size: 2.8vw;
  color: #666;
  margin-right: 1.5vw;
}

.wrapper .business li .business-info .business-info-promotion {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 2vw;
  padding-top: 2vw;
  border-top: 1px solid #f5f5f5;
}

.wrapper
  .business
  li
  .business-info
  .business-info-promotion
  .business-info-promotion-left {
  display: flex;
  align-items: center;
}

.wrapper
  .business
  li
  .business-info
  .business-info-promotion
  .business-info-promotion-left
  .business-info-promotion-left-incon {
  width: 4vw;
  height: 4vw;
  background-color: #70bc46;
  border-radius: 3px;
  font-size: 3vw;
  color: #fff;

  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.3vw 1vw;
  margin-right: 1.5vw;
}

.wrapper
  .business
  li
  .business-info
  .business-info-promotion
  .business-info-promotion-left
  p {
  color: #666;
  font-size: 3vw;
  margin-left: 2vw;
}

.wrapper
  .business
  li
  .business-info
  .business-info-promotion
  .business-info-promotion-right {
  display: flex;
  align-items: center;
  font-size: 2.5vw;
  color: #999;
}

.wrapper
  .business
  li
  .business-info
  .business-info-promotion
  .business-info-promotion-right
  p {
  margin-right: 2vw;
}

.empty-result {
  padding: 6vw 0;
  text-align: center;
  background: #fff;
  margin-top: 2vw;
}

.search-error {
  text-align: center;
  padding: 4vw;
  margin: 3vw;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.search-error p {
  color: #f56c6c;
  margin-bottom: 2vw;
  font-size: 3.5vw;
}

/* 自定义 Element Plus 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: none;
  padding: 0 15px;
}

:deep(.el-input__inner) {
  font-size: 3.5vw;
  color: #333;
}

/* 添加骨架屏加载效果 */
.business-skeleton {
  padding: 3vw;
  background: #fff;
  border-radius: 2vw;
  margin-bottom: 2vw;
}

/* 响应式布局优化 */
@media screen and (min-width: 768px) {
  .wrapper {
    max-width: 768px;
    margin: 0 auto;
  }
  
  .search-fixed-top {
    max-width: 768px;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>